package comxyp.controller.settings;
import comxyp.common.Constant;
import comxyp.common.ReturnData;
import comxyp.pojo.settings.Users;
import comxyp.service.settings.UsersService;
import comxyp.utils.DateUtils;
import comxyp.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;


@Controller
@RequestMapping("/settings")
public class UserController {
    @Autowired
    private UsersService usersService;
    @RequestMapping("/login")
    @ResponseBody
    public Object login(String loginAct, String loginPwd, String isRemPwd, HttpServletResponse response, HttpSession session){
        ReturnData returnData = new ReturnData();
        Users users = usersService.findUserAndPwd(loginAct, MD5Util.getMD5(loginPwd));
        if(users != null){
            /*设置成功状态码*/
            returnData.setCode(Constant.status2);
            //登录成功 保存用户信息
            session.setAttribute(Constant.user,users);
            //如果勾选了10天内免登录 那我们把密码和用户名存入cookie中
            if("true".equals(isRemPwd)){
                //把用户存入cookie中
                Cookie c1 = new Cookie("loginAct",loginAct);
                c1.setMaxAge(10*24*60*60);//设置时间
                response.addCookie(c1);//添加到浏览器中
                //把密码存入cookie中
                Cookie c2 = new Cookie("loginPwd",loginPwd);
                c2.setMaxAge(10*24*60*60);//设置时间
                response.addCookie(c2);//添加到浏览器中

            } else {
                //把没没有过期的cookie删除
                Cookie c1 = new Cookie("loginAct","1");
                c1.setMaxAge(0);
                response.addCookie(c1);
                //把没没有过期的cookie删除
                Cookie c2 = new Cookie("loginPwd","1");
                c2.setMaxAge(0);
                response.addCookie(c2);
            }
        } else{
            if(users==null){
                returnData.setCode(Constant.status1);
                returnData.setMsg("用户名或者密码错误");
            } else if(DateUtils.formateDateTime(new Date()).compareTo(users.getExpireTime())>0){
                //登录失败，账号已过期
                returnData.setCode(Constant.status1);
                returnData.setMsg("账号已过期");
            }else if("0".equals(users.getLockState())) {
                //登录失败，状态被锁定
                returnData.setCode(Constant.status1);
                returnData.setMsg("状态被锁定");
            }
        }
        return returnData;
    }

}
